package com.xindacloud.sms.adapter.service.sms.impl;

import com.cmtelecom.text.sdk.MessageBuilder;
import com.cmtelecom.text.sdk.MessagingClient;
import com.cmtelecom.text.sdk.models.Channel;
import com.cmtelecom.text.sdk.models.Response;
import com.xindacloud.sms.adapter.bo.SubmitMessageBO;
import com.xindacloud.sms.adapter.constant.CommonConstant;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.sms.ISubmitMessageService;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import com.xindacloud.sms.adapter.vo.SubmitMessageResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

@Service("cmSubmitMessageService")
@Slf4j
public class CmSubmitMessageServiceImpl implements ISubmitMessageService<SubmitMessageBO, SubmitMessageResultVO> {

    @Override
    public SubmitMessageResultVO submitMessage(SubmitMessageBO submitMessageBO) {

        final String messageId = UUID.randomUUID().toString().replaceAll("-", "");

        final String recipient = submitMessageBO.getRecipient();
        final String[] split = recipient.split(CommonConstant.SEPARATOR_STR);
        final String apiSecret = submitMessageBO.getApiSecret();
        final String messageBody = submitMessageBO.getMessageBody();
        final String senderId = submitMessageBO.getSenderId();


        try {
            final List<String> collect = Arrays.stream(split).map("00"::concat).collect(Collectors.toList());
            MessagingClient client = new MessagingClient(apiSecret);
            MessageBuilder messageBuilder = new MessageBuilder(messageBody, null, senderId,
                    String.join(CommonConstant.SEPARATOR_STR, collect).split(CommonConstant.SEPARATOR_STR));
            messageBuilder.WithAllowedChannels(new Channel[]{Channel.SMS});
            messageBuilder.WithReference(messageId);

            final Response.HttpResponseBody httpResponseBody = client.sendMessage(messageBuilder.Build());
            final Response.ResponseMessageDetail[] messages = httpResponseBody.messages;
            SubmitMessageResultVO submitMessageResultVO = new SubmitMessageResultVO();
            if (Objects.nonNull(messages) && messages.length > 0) {
                Arrays.asList(messages).forEach(mp -> {
                    submitMessageResultVO.setErrorText(mp.messageDetails);
                    submitMessageResultVO.setMessageId(messageId);
                    submitMessageResultVO.setNetwork("");
                    submitMessageResultVO.setSubmitStatus(0);

                });
            }
            return submitMessageResultVO;
        } catch (Exception e) {
            log.error("CM发送短信异常:{}", e.getMessage(), e);
            throw new ServiceException("短信发送异常".concat(e.getMessage()), UnionResultHelp.StatusEnum.BadRequest.code());
        }

    }

}
